/*
 * @Author: ReinerLau lk850593913@gmail.com
 * @Date: 2022-10-17 14:14:00
 * @LastEditors: ReinerLau lk850593913@gmail.com
 * @LastEditTime: 2023-02-16 11:16:01
 * @FilePath: \v2.0.0\src\composables\usePlayer.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { ref, onBeforeUnmount, Ref, onMounted } from "vue";

export default () => {
  const video: Ref<HTMLMediaElement> = ref(null);
  const SrsRtcPlayerAsync = (window as any).SrsRtcPlayerAsync;
  let srs;
  const loading = ref(false);

  interface CameraData {
    rtsp: string;
    id: number;
  }
  /**
   * @description: 初始化播放器
   * @return {*}
   */
  async function initPlayer(data: CameraData) {
    clearPlayer();
    const { id } = data;
    if (!id) return;
    playStream(data);
  }

  async function playStream(data: CameraData) {
    const { rtsp } = data;
    srs = new SrsRtcPlayerAsync();
    video.value.srcObject = srs.stream;
    await srs.play(rtsp);
  }

  onMounted(() => {
    loading.value = true;
    video.value.onplay = () => {
      loading.value = false;
    };
  });

  onBeforeUnmount(() => {
    clearPlayer();
  });

  function clearPlayer() {
    if (srs) {
      srs.close();
    }
    video.value.srcObject = null;
  }

  /**
   * @description: 全屏
   * @param {*} e 事件对象
   * @return {*}
   */
  function handleFullScreen(e: MouseEvent) {
    (e.target as Element).requestFullscreen();
  }

  return {
    initPlayer,
    video,
    handleFullScreen,
    loading,
  };
};
